require 'iconv'

class UserToolSetting < ActiveRecord::Base  
  
  belongs_to :user,:counter_cache => true
  belongs_to :tool,:counter_cache => true
  
  validates_presence_of :column,
    :user_id,
    :tool_id    
      
  def allow_sms?
    allow_sms == 'yes'
  end
  
  def allow_email?
    allow_email == 'yes'
  end
  
  def column_name
    Tool::COLUMN_NAMES[column]
  end
  
  def add_sms_count!(options = { :sms_count => 1})
    self.sms_count += options[:sms_count]
    self.smed_at = Time.now
    save(false)
  end
  
  def add_emails_count!(options = { :emails_count => 1})
    self.emails_count += options[:emails_count]
    self.emailed_at = Time.now
    save(false)
  end

  def send_sm_block!(args = {})
    if allow_sms?      
      logger.debug "user: #{user.try(:nick_name)} args[:mobile]:#{args[:mobile]}}"
      raise '发送失败，您尚未绑定手机号。' if(args[:mobile].blank? and (user.nil? or user.mobile.blank?))
      yield(args) if Rails.env != 'test'
      user.try(:add_sms_count!)
      add_sms_count! if not new_record?
    end
  end

  def send_email_block!
    if allow_email?
      yield if Rails.env != 'test'
      user.try(:add_emails_count!)
      add_emails_count! if not new_record?      
    end
  end
  
  def send_sm(pri = 1)
    begin
      send_sm!(pri)
    rescue Exception => error
      puts error
      logger.error error
    end
  end
  
  def send_email(options = {})
    begin
      send_email!(options)
    rescue Exception => error
      puts error
      logger.error error
    end    
  end
  
  def gbk_to_utf8(gbk_string)
    Iconv.iconv("UTF-8//IGNORE","GBK//IGNORE",gbk_string) 
  end
  
  def before_create
    self.position = (UserToolSetting.minimum(:position) || 0) - 1 if self.position == 0
  end
  
  def before_validation
    self.column ||= tool.default_column
  end 
  
  def self.all_by_current_user_by_column(column)
    find_all_by_user_id_and_column User.current_user_id, column, :order => 'position asc'
  end
  
  def self.all_by_ids(ids )
    ids ||= []
    ids.each_with_object([]) do |setting_id, settings|
      settings << find(setting_id) if exists?(setting_id)
    end
  end
  
  def month_customed!
    if not month_customed? and tool.month_fare > 0 and user.present?
      user.custom_money!(tool.month_fare) do
        Feed::MoneyToolMonthConsumed.create!(
          :user_id => user.id,
          :tool_id => tool.id,
          :subed_money => tool.month_fare,
          :money => user.money
        )
      end
      update_attributes! :consumed_on => Date.today
    end
  end
  
  def month_customed?
    consumed_on.present? and Date.today.year == consumed_on.year and Date.today.month == consumed_on.month
  end
  
  def self.month_customed_all!
    all( :conditions => [
          '(consumed_on is null or consumed_on < ?)',
          DateTime.now.beginning_of_month() 
        ]
    ).each do |setting|
      setting.month_customed!
    end
  end
end
